package com.ita.servlet.merchant;

import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ita.factory.MServiceFactory;
import com.ita.httpclient.CheckClient;
import com.ita.pojo.MenuType;
import com.ita.pojo.Merchant;
import com.ita.service.MenuService;
import com.ita.service.MerchantService;
import com.ita.util.Constant;
import com.ita.util.State;
import com.ita.util.TokenUtil;

@WebServlet("/sec/reflesh")
public class RefreshStateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MerchantService mService;
	private MenuService fService;

	public RefreshStateServlet() {
		mService = MServiceFactory.getMerchantService();
		fService = MServiceFactory.getMenuService();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		boolean r = TokenUtil.getInstance().isRsubmit((String)session.getAttribute("token"),request);
		
		if(r){
			request.setAttribute("info", "Dont ReSubmit!Pls wait");
			request.getRequestDispatcher("remind.jsp").forward(request,
					response);
			return;
		}

//		HttpSession session = request.getSession();
		Merchant m = (Merchant) session.getAttribute("m");
		CheckClient client = new CheckClient(m.getId());
		State s = client.getState();
		m = mService.loadMerchant(m.getName());
		request.getSession().setAttribute("m", m);
		if (s == State.BLOCK) {
			request.getSession().setAttribute("m_state", "Blocked");
			response.sendRedirect("block.jsp");
			return;
		}
		if (s == State.FAIL) {
			request.getSession().setAttribute("m_state", "Check Fail");
			request.getSession().setAttribute("msg",Constant.REASON);
			response.sendRedirect("info.jsp");
			return;
		}

		if (s == State.DEFAULT) {
			request.getSession().setAttribute("m_state", "Unhandle");
			response.sendRedirect("info.jsp");
			return;
		}
		if (s == State.ERROR) {
			response.sendRedirect("../error.jsp");
			return;
		}

		if (s == State.PASS) {
			List<MenuType> foodTypes = fService.loadMenuType();

			request.getSession().setAttribute("food_type", foodTypes);
			request.getSession().setAttribute("m_state", "Success");

			response.sendRedirect("meal/food");
			return;
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
